package tom.webflux.handler;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import tom.webflux.model.User;
import tom.webflux.service.UserService;

import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;

/**
 * @author ZHUFEIFEI
 */
@Component
public class UserHandler {

    @Autowired
    private UserService userService;

    public Mono<ServerResponse> findOne(ServerRequest request) {
        //
        return this.userService.findById(request)
                .flatMap((user) -> ServerResponse.ok().body(BodyInserters.fromObject(user)))
                .switchIfEmpty(ServerResponse.notFound().build());
    }

    public Mono<ServerResponse> findAll(ServerRequest request) {
        //with response body
        return ServerResponse.ok().body(this.userService.findAll(), User.class);
    }

    public Mono<ServerResponse> addUser(ServerRequest request) {
        //build with no body
        return ServerResponse.status(HttpStatus.CREATED).build(this.userService.create(request));
    }

    public Mono<ServerResponse> removeUser(ServerRequest request) {
        return ServerResponse.ok().build(this.userService.delete(request));
    }

    /**
     * 服务器不断推流给客户端, 链接一直保持
     * @param request
     * @return
     */
    public Mono<ServerResponse> tick(ServerRequest request) {
        //content-type类型为TEXT_EVENT_STREAM，表示SSE(server sent event)类型
        //代表text/event-stream
        //每秒钟返回一个日期时间不间断
        return ServerResponse.ok().contentType(MediaType.TEXT_EVENT_STREAM)
                .body(
                        Flux.interval(Duration.ofSeconds(1L))
                        .map(t -> SimpleDateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()))
                        , String.class);
    }
}
